package com.qianfeng.smartdevice.service.impl;


//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼            BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qianfeng.smartdevice.cache.AreaCache;
import com.qianfeng.smartdevice.constants.ResultCode;
import com.qianfeng.smartdevice.event.AreanChangeEvent;
import com.qianfeng.smartdevice.exceptions.AddErrorException;
import com.qianfeng.smartdevice.exceptions.DeleteErrorException;
import com.qianfeng.smartdevice.exceptions.MyBaseErrorxception;
import com.qianfeng.smartdevice.exceptions.UpdateErrorException;
import com.qianfeng.smartdevice.mapper.AreaMapper;
import com.qianfeng.smartdevice.pojo.Area;
import com.qianfeng.smartdevice.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by jackiechan on 2020/12/12 23:08
 *
 * @Author jackiechan
 */
@Service
@Transactional
public class AreaServiceImpl implements AreaService {
    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private ApplicationContext context;

    @Autowired
    private AreaCache areaCache;
    @Autowired
    private AreanChangeEvent event;

    @Override
    public void addArea(Area area) {
        if (area == null) {
            throw new AddErrorException("数据不能为空", ResultCode.NULL_DATA);
        }

        try {
            areaMapper.addArea(area);
            context.publishEvent(event);//更新缓存
        } catch (Exception e) {
            e.printStackTrace();
            throw new AddErrorException("添加失败", ResultCode.ERROR);
        }

    }

    @Override
    public void updateArea(Area area) {
        if (area == null || area.isEmpty()) {
            throw new AddErrorException("数据不能为空", ResultCode.NULL_DATA);
        }
        if ("0".equalsIgnoreCase(area.getStatus())) {//如果也要更新状态为禁用
            List<Area> areaList = getAreaByParentId(area.getId());//获取以当前区域 id 为父 id 的区域,如果有则不允许更新为禁用
            if (areaList.size() != 0) {
                throw new UpdateErrorException("当前区域的子区域不为空,无法禁用", ResultCode.DATA_NOT_EPTY);
            }
        }

        try {
            areaMapper.updateArea(area);
            context.publishEvent(event);//更新缓存
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpdateErrorException("更新失败", ResultCode.ERROR);

        }
    }

    @Override
    public void deleteAreas(List<String> ids) {
        if (ids == null || ids.size() == 0) {
            throw new DeleteErrorException("没有传递 id", ResultCode.NULL_DATA);
        }

        try {
            areaMapper.deleteAreas(ids);
            context.publishEvent(event);//更新缓存
        } catch (Exception e) {
            e.printStackTrace();
            throw new DeleteErrorException("删除失败", ResultCode.ERROR);
        }
    }

    @Override
    public Area getAreaById(Long id) {
        if (id == null || id == 0) {
            throw new MyBaseErrorxception("没有传递 id", ResultCode.NULL_DATA);
        }

        try {
           // Area area = areaMapper.getAreaById(id);
            Area area = areaCache.get(id);
            if (area == null) {
                throw new MyBaseErrorxception("没有查询到结果", ResultCode.ERROR);
            }
            return area;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyBaseErrorxception("查询失败", ResultCode.ERROR);
        }
    }

    @Override
    public List<Area> getAreaByParentId(Long id) {
        if (id == null || id == 0) {
            throw new MyBaseErrorxception("没有传递 id", ResultCode.NULL_DATA);
        }

        try {
           // List<Area> areaList = areaMapper.getAreaByParentId(id);
            List<Area> allData = areaCache.getAllData();//从缓存查询所有数据
            List<Area> areaList = allData.stream().filter(area -> id == area.getParentid()).collect(Collectors.toList());//获取父id和当前id一样的数据
            return areaList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyBaseErrorxception("查询失败", ResultCode.ERROR);

        }
    }

    @Override
    public PageInfo<Area> getAllAreas(int pageNum, int pageSize, String exludeId, String areanname, int status) {
        PageHelper.startPage(pageNum, pageSize);
        try {
            //TODO 参考分类的查询方式,此处忽略未写
            List<Area> areaList = areaMapper.getAllAreas(exludeId, areanname, status);
            return new PageInfo<>(areaList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyBaseErrorxception("查询失败", ResultCode.ERROR);
        }
    }

    /**
     * 获取没有父的那些区域
     * @param status
     * @return
     */
    @Override
    public List<Area> getAllFirstParentAreas(String status) {

        try {
//            return areaMapper.getAllFirstParentAreas(status);
            List<Area> allData = areaCache.getAllData();
            List<Area> areaList = allData.stream().filter(area ->

                    {
                        if (status=="0"||status=="1") {
                            return area.getParentid() == null && area.getStatus() == status;
                        }
                        return area.getParentid() == null;
                    }

            ).collect(Collectors.toList());
            return areaList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyBaseErrorxception("查询异常", ResultCode.ERROR);
        }
    }
}
